package logger

import (
	"context"
	"github.com/apache/rocketmq-client-go/v2/primitive"
	"go.uber.org/zap"
	"gobase/rocketmq"
	"io"
)

type LogRocketMQ struct {
	producer *rocketmq.MqProducer
	Topic    string
	Group    string
	Address  []string
	Level    *Level
	fields   []zap.Field
}

func (l *LogRocketMQ) Write(p []byte) (int, error) {
	var err error
	//fmt.Println("Body1 ======>:", string(p))
	if l.producer.RetryNum < 1 {
		return 0, nil
	}
	MqMsg := rocketmq.NewMQMessage(l.Topic, "logs", l.Topic, p, 0)
	_, err = l.producer.SendAsyncMessage(MqMsg, func(ctx context.Context, result *primitive.SendResult, e error) {
		if e != nil {
			return
		}
	})
	if err != nil {
		//fmt.Println("MQ 异步发送消息 err: ", err)
		return 0, err
	}
	return len(p), nil
}

func getRocketMQWriter(topic string, group string, SrvAddr []string, fields ...zap.Field) (io.Writer, error) {
	lr := &LogRocketMQ{
		Topic:  topic,
		Group:  group,
		fields: fields,
	}
	lr.producer = rocketmq.NewMQProducer(topic, group, SrvAddr)
	return lr, nil
}
